1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.io;
18
19 import static com.google.common.base.Preconditions.checkNotNull;
20
21 import java.io.Closeable;
22 import java.io.Flushable;
23 import java.io.IOException;
24 import java.io.Writer;
25
26 import javax.annotation.Nullable;
27
28
29
30
31
32
33
34
35
36
37 class AppendableWriter extends Writer {
38 private final Appendable target;
39 private boolean closed;
40
41
42
43
44
45
46 AppendableWriter(Appendable target) {
47 this.target = checkNotNull(target);
48 }
49
50
51
52
53
54 @Override public void write(char cbuf[], int off, int len)
55 throws IOException {
56 checkNotClosed();
57
58
59 target.append(new String(cbuf, off, len));
60 }
61
62 @Override public void flush() throws IOException {
63 checkNotClosed();
64 if (target instanceof Flushable) {
65 ((Flushable) target).flush();
66 }
67 }
68
69 @Override public void close() throws IOException {
70 this.closed = true;
71 if (target instanceof Closeable) {
72 ((Closeable) target).close();
73 }
74 }
75
76
77
78
79
80
81 @Override public void write(int c) throws IOException {
82 checkNotClosed();
83 target.append((char) c);
84 }
85
86 @Override public void write(@Nullable String str) throws IOException {
87 checkNotClosed();
88 target.append(str);
89 }
90
91 @Override public void write(@Nullable String str, int off, int len) throws IOException {
92 checkNotClosed();
93
94 target.append(str, off, off + len);
95 }
96
97 @Override public Writer append(char c) throws IOException {
98 checkNotClosed();
99 target.append(c);
100 return this;
101 }
102
103 @Override public Writer append(@Nullable CharSequence charSeq) throws IOException {
104 checkNotClosed();
105 target.append(charSeq);
106 return this;
107 }
108
109 @Override public Writer append(@Nullable CharSequence charSeq, int start, int end)
110 throws IOException {
111 checkNotClosed();
112 target.append(charSeq, start, end);
113 return this;
114 }
115
116 private void checkNotClosed() throws IOException {
117 if (closed) {
118 throw new IOException("Cannot write to a closed writer.");
119 }
120 }
121 }